package com.lanchetech.user.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaSecCheckService;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.*;
import com.lanchetech.common.enums.*;
import com.lanchetech.common.exception.ResultCodeException;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import com.lanchetech.service.ExpService;
import com.lanchetech.user.service.CourseService;
import com.lanchetech.user.service.MiniappService;
import jodd.util.StringUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    HomeworkMapper homeworkMapper;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    ColumnsMapper columnsMapper;

    @Autowired
    ColumnCourseAuthMapper columnCourseAuthMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    CourseCommentGoodMapper courseCommentGoodMapper;

    @Autowired
    CourseCommentMapper courseCommentMapper;

    @Autowired
    CourseGoodsMapper courseGoodsMapper;

    @Autowired
    CourseStudyMapper courseStudyMapper;

    @Autowired
    ColumnCourseCollectMapper columnCourseCollectMapper;

    @Autowired
    ExpService expService;

    @Autowired
    HonorMapper honorMapper;

    @Autowired
    ExpFlowMapper expFlowMapper;

    @Autowired
    MiniappService miniappService;

    @Override
    public ResultData<Columns> getColumnsDetail(Long id) {
        return new ResultData<>(columnsMapper.selectByPrimaryKey(id));
    }

    @Override
    public ResultData<BasePageResp<Columns>> getColumnsPage(PageReq req) {
        req.setStatus(ToggleEnum.ON.getStatus());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Columns> list = columnsMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<List<Columns>> getColumnsList() {
        return new ResultData<>(columnsMapper.findAllNotDeleted());
    }

    @Override
    public ResultData<CourseVO> getCourseDetail(User user, Long id) {
        try {

            Course result = courseMapper.selectByPrimaryKey(id);
            CourseVO course = new CourseVO();
            BeanUtils.copyProperties(result, course);

            if (user != null) {
                course.setHasGood(courseGoodsMapper.findOneByUserIdAndCourseId(user.getId(), id) != null);
            }

            // 公开
            if (CourseAuthEnum.PUBLIC.getType().equals(course.getAuth())) {
                readCourse(course, user);
                return new ResultData<>(course);
            }

            if (user == null) {
                throw new ResultCodeException(ResultCode.NOT_BUY_COURSE);
            }

            // 仅会员可见
            if (CourseAuthEnum.ONLY_MEMBER.getType().equals(course.getAuth())) {
                if (course.getVips() != null && course.getVips().contains("," + user.getLevel() + ",")) {
                    readCourse(course, user);
                    return new ResultData<>(course);
                }
                throw new ResultCodeException(ResultCode.YOU_ARE_NOT_MEMBER_OR_MEMBER_NOT_VISIBLE);
            }

            ColumnCourseAuth columnAuth = columnCourseAuthMapper.findOneByUserIdAndColumnIdAndType(user.getId(), course.getColumnId(), ColumnCourseAuthTypeEnum.COLUMN.getType());

            ColumnCourseAuth courseAuth = columnCourseAuthMapper.findOneByUserIdAndCourseIdAndType(user.getId(), id, ColumnCourseAuthTypeEnum.COLUMN.getType());

            boolean hasAuth = columnAuth != null || courseAuth != null;

            if (CourseAuthEnum.ONLY_BUY.getType().equals(course.getAuth())) {
                if (hasAuth) {
                    readCourse(course, user);
                    return new ResultData<>(course);
                }
                throw new ResultCodeException(ResultCode.NOT_BUY_COURSE);
            }

            if (CourseAuthEnum.MEMBER_OR_BUY.getType().equals(course.getAuth())) {
                if (course.getVips() != null && course.getVips().contains("," + user.getLevel() + ",")) {
                    readCourse(course, user);
                    return new ResultData<>(course);
                }

                if (hasAuth) {
                    readCourse(course, user);
                    return new ResultData<>(course);
                }
                throw new ResultCodeException(ResultCode.NOT_BUY_COURSE);
            }
            throw new ResultCodeException(ResultCode.NOT_BUY_COURSE);
        } catch (ResultCodeException e) {
            ResultData resultData = new ResultData();
            resultData.setResultCode(e.getResultCode());
            return resultData;
        }
    }

    private void readCourse(CourseVO course, User user) {
        // 阅读数量+1
        courseMapper.addOneViewsById(course.getId());

        // 创建课程学习记录
        if (user != null) {
            CourseStudy courseStudy = courseStudyMapper.findOneByUserIdAndCourseId(user.getId(), course.getId());
            if (courseStudy == null) {
                courseStudyMapper.insert(CourseStudy.builder()
                        .userId(user.getId())
                        .columnId(course.getColumnId())
                        .courseId(course.getId())
                        .createdAt(new Date())
                        .build());
                // 统计学习人数
                courseMapper.updateStudyCountById(courseStudyMapper.countByCourseId(course.getId()), course.getId());

                columnsMapper.updateStudyCountById(courseMapper.sumByColumnId(course.getColumnId()), course.getColumnId());
            } else {
                courseStudy.setCreatedAt(new Date());
                courseStudyMapper.updateByPrimaryKey(courseStudy);
            }

            ColumnCourseCollect columnCourseCollect = columnCourseCollectMapper.findOneByUserIdAndCourseIdAndType(user.getId(), course.getId(), ColumnCourseAuthTypeEnum.COURSE.getType());

            course.setHasCollect(columnCourseCollect != null);

            Homework homework = homeworkMapper.findOneByUserIdAndCourseId(user.getId(), course.getId());
            course.setDoneHomework(homework == null ? null : homework.getId());

            // 发放学分
            expService.createExpFlow(user, course.getId(), ExpTypeEnum.STUDY_COURSE);
        }

        // 获取上一课和下一课信息
        List<Course> list = courseMapper.findAllByColumnIdAndStatusAndDeleted(course.getColumnId(), ToggleEnum.ON.getStatus(), DeletedEnum.DEFAULT.getStatus());

        if(!CollectionUtils.isEmpty(list)){
            int current = 0;
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getId().equals(course.getId())){
                    current = i;
                }
            }

            if(current > 0){
                course.setPrevCourse(list.get(current - 1));
            }
            if(current + 1 < list.size()){
                course.setNextCourse(list.get(current + 1));
            }
        }
    }

    @Override
    public ResultData<BasePageResp<CourseVO>> getCoursePage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        req.setStatus(ToggleEnum.ON.getStatus());
        if (req.getColumnId() == null) {
            ResultData resultData = new ResultData();
            resultData.setResultCode(ResultCode.FAIL);
            return resultData;
        }

        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Course> list = courseMapper.findAllPage(req);
        List<CourseVO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            ColumnCourseAuth columnAuth = columnCourseAuthMapper.findOneByUserIdAndColumnIdAndType(user.getId(), req.getColumnId(), ColumnCourseAuthTypeEnum.COLUMN.getType());
            Map<Long, Boolean> map = new HashMap<>();
            if (columnAuth == null) {
                List<ColumnCourseAuth> columnCourseAuthList = columnCourseAuthMapper.findAllByUserIdAndColumnIdAndType(user.getId(), req.getColumnId(), ColumnCourseAuthTypeEnum.COURSE.getType());
                columnCourseAuthList.stream().forEach(item -> map.put(item.getCourseId(), true));
            }

            list.stream().forEach(item -> {
                CourseVO vo = new CourseVO();
                BeanUtils.copyProperties(item, vo, "video", "audio", "content");
                vo.setHasAuth(columnAuth != null || map.containsKey(item.getId()));
                vo.setHasVideo(!StringUtils.isEmpty(item.getVideo()));
                result.add(vo);
            });
        }

        return PageHelpUtil.buildPage(result, page);
    }

    @Override
    public ResultData<CourseVO> getCoursePrevAndNext(Long id) {
        Course result = courseMapper.selectByPrimaryKey(id);

        CourseVO course = new CourseVO();
        course.setId(result.getId());
        course.setColumnId(result.getColumnId());

        // 获取上一课和下一课信息
        List<Course> list = courseMapper.findAllByColumnIdAndStatusAndDeleted(course.getColumnId(), ToggleEnum.ON.getStatus(), DeletedEnum.DEFAULT.getStatus());

        if(!CollectionUtils.isEmpty(list)){
            int current = 0;
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getId().equals(course.getId())){
                    current = i;
                }
            }

            if(current > 0){
                course.setPrevCourse(list.get(current - 1));
            }
            if(current + 1 < list.size()){
                course.setNextCourse(list.get(current + 1));
            }
        }
        return new ResultData<>(course);
    }

    @Override
    public ResultData<List<CourseVO>> getColumnCourseList(Long columnId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        PageReq req = new PageReq();
        req.setColumnId(columnId);
        req.setStatus(ToggleEnum.ON.getStatus());

        List<Course> list = courseMapper.findAllPage(req);
        List<CourseVO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            ColumnCourseAuth columnAuth = columnCourseAuthMapper.findOneByUserIdAndColumnIdAndType(user.getId(), req.getColumnId(), ColumnCourseAuthTypeEnum.COLUMN.getType());
            Map<Long, Boolean> map = new HashMap<>();
            if (columnAuth == null) {
                List<ColumnCourseAuth> columnCourseAuthList = columnCourseAuthMapper.findAllByUserIdAndColumnIdAndType(user.getId(), req.getColumnId(), ColumnCourseAuthTypeEnum.COURSE.getType());
                columnCourseAuthList.stream().forEach(item -> map.put(item.getCourseId(), true));
            }

            list.stream().forEach(item -> {
                CourseVO vo = new CourseVO();
                BeanUtils.copyProperties(item, vo, "video", "audio", "content");
                vo.setHasAuth(columnAuth != null || map.containsKey(item.getId()));
                vo.setHasVideo(item.getVideo() != null);
                result.add(vo);
            });
        }

        return new ResultData<>(result);
    }

    @Override
    public ResultData<BasePageResp<ColumnCourseAuthVO>> getColumnCourseAuthPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        req.setUserId(user.getId());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<ColumnCourseAuthVO> list = columnCourseAuthMapper.findAllPage(req);

        if (!CollectionUtils.isEmpty(list)) {
            List<Long> columnList = new ArrayList<>();
            List<Long> courseList = new ArrayList<>();
            list.stream().forEach(item -> {
                columnList.add(item.getColumnId());
                if (ColumnCourseAuthTypeEnum.COURSE.getType().equals(item.getType())) {
                    courseList.add(item.getCourseId());
                }
            });
            Map<Long, Columns> columnMap = daoService.getColumnMap(columnList);
            Map<Long, Course> courseMap = courseList.size() > 0 ? daoService.getCourseMap(courseList) : new HashMap<>();

            list.stream().forEach(item -> {
                item.setColumnTitle(columnMap.get(item.getColumnId()).getTitle());
                item.setColumnImage(columnMap.get(item.getColumnId()).getImage());
                item.setColumnDescription(columnMap.get(item.getColumnId()).getDescription());
                if (ColumnCourseAuthTypeEnum.COURSE.getType().equals(item.getType())) {
                    item.setCourseTitle(courseMap.get(item.getCourseId()).getTitle());
                    item.setCourseImage(courseMap.get(item.getCourseId()).getImageList());
                    item.setCourseDescription(courseMap.get(item.getCourseId()).getDescription());
                }
            });
        }

        return PageHelpUtil.buildPage(list, page);
    }


    @Override
    public BaseResp deleteCourseComment(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        CourseComment result = courseCommentMapper.selectByPrimaryKey(id);

        courseCommentMapper.deleteByUserIdAndId(user.getId(), id);
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<CourseCommentPageVO>> getCourseCommentPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CourseComment> list = courseCommentMapper.findAllPage(req);
        List<CourseCommentPageVO> result = new ArrayList<>();
        if (!org.springframework.util.CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(CourseComment::getUserId).collect(Collectors.toList()));
            Map<Long, BasePageResp<CourseCommentPageVO>> map = new HashMap<>();
            Map<Long, Boolean> goodsMap = new HashMap<>();

            // 如果是获取主评论分页
            if (req.getCommentId().equals(0L)) {
                List<Long> commentIds = new ArrayList<>();
                List<Long> goodsCommentIds = new ArrayList<>();
                list.stream().forEach(item -> {
                    if (item.getCommentCount() > 0 && !commentIds.contains(item.getId())) {
                        commentIds.add(item.getId());
                    }
                    if (item.getGoodCount() > 0 && !goodsCommentIds.contains(item.getId())) {
                        goodsCommentIds.add(item.getId());
                    }
                });

                if (commentIds.size() > 0) {
                    // 逐个获取回复的分页
                    commentIds.stream().forEach(item -> {
                        PageReq pageReq = new PageReq();
                        pageReq.setPageNo(1);
                        pageReq.setPageSize(10);
                        pageReq.setCommentId(item);
                        pageReq.setCourseId(req.getCourseId());
                        map.put(item, getCourseCommentPage(pageReq).getValue());
                    });
                }
                if (goodsCommentIds.size() > 0) {
                    List<CourseCommentGood> courseGoodList = courseCommentGoodMapper.findAllByUserIdAndCommentIds(user.getId(), goodsCommentIds);
                    if (!org.springframework.util.CollectionUtils.isEmpty(courseGoodList)) {
                        courseGoodList.stream().forEach(item -> goodsMap.put(item.getCommentId(), true));
                    }
                }
            }

            list.stream().forEach(item -> {
                CourseCommentPageVO vo = new CourseCommentPageVO();
                BeanUtils.copyProperties(item, vo);
                vo.setAvatar(userMap.get(item.getUserId()).getAvatar());
                vo.setNickname(userMap.get(item.getUserId()).getNickname());

                if (req.getCommentId().equals(0L)) {
                    vo.setReplyPage(map.get(item.getId()));
                    vo.setIsGood(goodsMap.containsKey(item.getId()));
                }
                result.add(vo);
            });
        }
        return PageHelpUtil.buildPage(result, page);
    }

    @Override
    public BaseResp editCourseComment(CourseComment req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        WxMaSecCheckService wxMaSecCheckService = miniappService.wxMaSecCheckService();
        try {
            if(!StringUtils.isEmpty(req.getContent())){
                if(!wxMaSecCheckService.checkMessage(req.getContent())){
                    return new BaseResp(ResultCode.COMMENT_CONTENT_ERROR);
                }
            }
        } catch (WxErrorException e) {
            return new BaseResp(ResultCode.COMMENT_CONTENT_ERROR);
        }

        req.setUserId(user.getId());
        req.setGoodCount(0L);
        req.setCommentCount(0L);
        req.setCreatedAt(new Date());
        courseCommentMapper.insert(req);

        // 发放学分
        expService.createExpFlow(user, req.getCourseId(), ExpTypeEnum.COMMENT);

        if (req.getCommentId() > 0) {
            // 增加评论数量
            courseCommentMapper.addOneCommentCountById(req.getCommentId());
        }
        return new BaseResp();
    }

    @Override
    public BaseResp toggleCourseCommentGood(Long courseId, Long commentId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        CourseCommentGood courseGood = courseCommentGoodMapper.findOneByCourseIdAndCommentIdAndUserId(courseId, commentId, user.getId());

        if (courseGood == null) {
            CourseCommentGood result = CourseCommentGood.builder()
                    .courseId(courseId)
                    .userId(user.getId())
                    .commentId(commentId)
                    .createdAt(new Date())
                    .build();
            courseCommentGoodMapper.insert(result);
            // 增加点赞数量
            courseCommentMapper.addOneGoodCountById(result.getCommentId());
        } else {
            // 删除
            if (courseGood.getUserId().equals(user.getId())) {
                courseCommentGoodMapper.deleteByPrimaryKey(courseGood.getId());
                // 减少点赞数量
                courseCommentMapper.subOneGoodCountById(courseGood.getCommentId());
            }
        }
        return new BaseResp();
    }

    @Override
    public BaseResp createColumnCourseCollect(ColumnCourseCollect req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ColumnCourseCollect res = null;
        if(ColumnCourseAuthTypeEnum.COURSE.getType().equals(req.getType())){
            res = columnCourseCollectMapper.findOneByUserIdAndCourseIdAndType(user.getId(), req.getCourseId(), ColumnCourseAuthTypeEnum.COURSE.getType());
        }else{
            res = columnCourseCollectMapper.findOneByUserIdAndColumnIdAndType(user.getId(), req.getColumnId(), ColumnCourseAuthTypeEnum.COLUMN.getType());
        }

        if(res == null){
            req.setUserId(user.getId());
            req.setCreatedAt(new Date());
            columnCourseCollectMapper.insert(req);
        }
        return new BaseResp();
    }

    @Override
    public BaseResp deleteColumnCourseCollect(ColumnCourseCollect req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ColumnCourseCollect res = null;
        if(ColumnCourseAuthTypeEnum.COURSE.getType().equals(req.getType())){
            res = columnCourseCollectMapper.findOneByUserIdAndCourseIdAndType(user.getId(), req.getCourseId(), ColumnCourseAuthTypeEnum.COURSE.getType());
        }else{
            res = columnCourseCollectMapper.findOneByUserIdAndColumnIdAndType(user.getId(), req.getColumnId(), ColumnCourseAuthTypeEnum.COLUMN.getType());
        }

        if(res != null){
            columnCourseCollectMapper.deleteByPrimaryKey(res.getId());
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<ColumnCourseCollectPageVO>> getColumnCourseCollectPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        req.setUserId(user.getId());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<ColumnCourseCollectPageVO> list = columnCourseCollectMapper.findAllPage(req);

        if (!CollectionUtils.isEmpty(list)) {
            List<Long> columnList = new ArrayList<>();
            List<Long> courseList = new ArrayList<>();
            list.stream().forEach(item -> {
                columnList.add(item.getColumnId());
                if (ColumnCourseAuthTypeEnum.COURSE.getType().equals(item.getType())) {
                    courseList.add(item.getCourseId());
                }
            });
            Map<Long, Columns> columnMap = daoService.getColumnMap(columnList);
            Map<Long, Course> courseMap = courseList.size() > 0 ? daoService.getCourseMap(courseList) : new HashMap<>();

            list.stream().forEach(item -> {
                item.setColumnTitle(columnMap.get(item.getColumnId()).getTitle());
                item.setColumnImage(columnMap.get(item.getColumnId()).getImage());
                item.setColumnDescription(columnMap.get(item.getColumnId()).getDescription());
                if (ColumnCourseAuthTypeEnum.COURSE.getType().equals(item.getType())) {
                    item.setCourseTitle(courseMap.get(item.getCourseId()).getTitle());
                    item.setCourseImage(courseMap.get(item.getCourseId()).getImageList());
                    item.setCourseDescription(courseMap.get(item.getCourseId()).getDescription());
                }
            });
        }

        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<CourseHomeworkVO> getCourseHomework(Long courseId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        CourseHomeworkVO vo = new CourseHomeworkVO();
        vo.setFeature(courseMapper.selectByPrimaryKey(courseId).getFeature());
        vo.setHomework(homeworkMapper.findOneByUserIdAndCourseId(user.getId(), courseId));
        return new ResultData<>(vo);
    }

    @Override
    public BaseResp editHomework(Homework req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if(req.getId() == null){
            req.setUserId(user.getId());
            req.setCreatedAt(new Date());
            req.setUpdatedAt(new Date());
            homeworkMapper.insert(req);

            // 发放学分
            expService.createExpFlow(user, req.getCourseId(), ExpTypeEnum.DO_HOMEWORK);
        }else{
            Homework result = homeworkMapper.selectByPrimaryKey(req.getId());
            if(result == null || !result.getUserId().equals(user.getId())){
                return new BaseResp(ResultCode.FAIL);
            }

            req.setUpdatedAt(new Date());
            homeworkMapper.updateByPrimaryKeySelective(req);
        }

        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<HomeworkVO>> getHomeworkPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setUserId(user.getId());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<HomeworkVO> list = homeworkMapper.findAllPage(req);

        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, Course> courseMap = daoService.getCourseMap(list.stream().map(Homework::getCourseId).collect(Collectors.toList()));

            list.stream().forEach(item -> {
                item.setCourseTitle(courseMap.get(item.getCourseId()).getTitle());
                item.setCourseImage(courseMap.get(item.getCourseId()).getImageList());
            });
        }

        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<Honor>> getHonorPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setUserId(user.getId());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Honor> list = honorMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<ExpFlow>> getExpFlowPage(PageReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setUserId(user.getId());
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<ExpFlow> list = expFlowMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp toggleCourseGoods(Long courseId, Integer goods) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        CourseGoods courseGoods = courseGoodsMapper.findOneByUserIdAndCourseId(user.getId(), courseId);
        if (goods.equals(1)) {
            if (courseGoods == null) {
                // 加1个赞
                courseGoodsMapper.insert(CourseGoods.builder()
                        .userId(user.getId())
                        .courseId(courseId)
                        .createdAt(new Date())
                        .build());

                courseMapper.addOneGoodsById(courseId);
            }
        } else {
            if (courseGoods != null) {
                // 减1个赞
                courseGoodsMapper.deleteByPrimaryKey(courseGoods.getId());

                courseMapper.subOneGoodsById(courseId);
            }
        }
        return new BaseResp();
    }
}